package com.css.devops.monitor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

public class JenkinsViewManager3 {

    // 连接 Jenkins 需要设置的信息
    static final String JENKINS_URL = "http://192.168.94.1:18080";
    static final String JENKINS_USERNAME = "admin";
    static final String JENKINS_PASSWORD = "p@ssw0rd";

    /**
     * 使用 HTTP 请求删除 Jenkins 中的 Job
     */
    public static void deleteJob(String jobName) {
        try {
            // 构造 API URL
            String urlStr = JENKINS_URL + "/job/" + jobName + "/doDelete";
            URL url = new URL(urlStr);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");

            // 设置授权头
            String auth = JENKINS_USERNAME + ":" + JENKINS_PASSWORD;
            String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
            connection.setRequestProperty("Authorization", "Basic " + encodedAuth);

            // 发送请求
            int responseCode = connection.getResponseCode();
            StringBuilder response = new StringBuilder();
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
            }

            // 输出响应内容和状态码
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("Job '" + jobName + "' has been deleted.");
            } else {
                System.out.println("Failed to delete job. Response Code: " + responseCode);
                System.out.println("Response Body: " + response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            // 目标 Job 名称
            String jobName = "test-job";

            // 删除 Job
            deleteJob(jobName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


